package net.gyapp.markim.core;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.easyder.wrapper.utils.LogUtils;

import net.gyapp.markim.AppConfig;
import net.gyapp.markim.WrapperApplication;
import net.gyapp.markim.core.entity.ConversationEntity;
import net.gyapp.markim.core.entity.FriendsEntity;
import net.gyapp.markim.core.entity.GroupEntity;
import net.gyapp.markim.core.entity.IEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.core.entity.MessageEntity;
import net.gyapp.markim.core.entity.UserEntity;
import net.gyapp.markim.core.reponse.ChatResponse;
import net.gyapp.markim.core.reponse.ImResponse;
import net.gyapp.markim.core.reponse.LoginResponse;
import net.gyapp.markim.core.reponse.OfflineMessageResponse;
import net.gyapp.markim.core.reponse.UserGroupResponse;
import net.gyapp.markim.dao.ConversationEntityDao;
import net.gyapp.markim.dao.DBManager;
import net.gyapp.markim.dao.FriendsEntityDao;
import net.gyapp.markim.dao.GroupEntityDao;
import net.gyapp.markim.dao.MemberEntityDao;
import net.gyapp.markim.dao.MessageEntityDao;
import net.gyapp.markim.module.basic.event.ResponseChanged;
import net.gyapp.markim.module.basic.event.ResponseIml;
import net.gyapp.markim.module.mine.vo.MemberListVo;
import net.gyapp.markim.module.mine.vo.MemberVo;
import net.gyapp.markim.utils.DateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.query.QueryBuilder;
import org.jim.common.packets.ChatType;
import org.jim.common.packets.Command;
import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Auther:  winds
 * Email:   heardown@163.com
 * Date:    2018/7/18.
 * Desc:
 */

public class ImHelper {

    /**
     * 判断是否是自己发的信息
     *
     * @param id
     * @return
     */
    public static boolean isSelf(String id) {
        if (!TextUtils.isEmpty(id) && WrapperApplication.isLogin()) {
            return WrapperApplication.getMember().userInfo.userName.equalsIgnoreCase(id);
        }
        return false;
    }

    /**
     * 获取当前账号的ID
     * 此Id 是登陆的账号名 发送消息的发送id
     *
     * @return
     */
    public static String getSelf() {
        return WrapperApplication.getMember() != null ? WrapperApplication.getMember().userInfo.userName : "";
    }

    /**
     * 获取用户的用户id  此id用来关联用户
     *
     * @return
     */
    public static Long getSelfUserId() {
        return Long.valueOf(WrapperApplication.getMember() != null ? WrapperApplication.getMember().userInfo.userId : 0);
    }

    /**
     * 获取当前账号头像
     *
     * @return
     */
    public static String getSelfAvatar() {
        return WrapperApplication.getMember() != null ? WrapperApplication.getMember().userInfo.userAvatar : "";
    }

    public static String getSelfNick() {
        return WrapperApplication.getMember() != null ? WrapperApplication.getMember().userInfo.nick : "";
    }


    /**
     * 获取当前时间戳
     *
     * @return
     */
    public static long getTimestamp() {
        return System.currentTimeMillis();
    }


    public static String formatTime(long time, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern(pattern);
        return format.format(time);
    }

    public static String formatTime(long time) {
        if (DateUtils.isToday(time)) {
            return formatTime(time, "HH:mm");
        }
        return formatTime(time, "MM-dd HH:mm");
    }

    public static String getActualPicturePath(org.json.JSONObject response) throws JSONException {
        return AppConfig.QINIU_PICTURE_PATH + response.getString("key");
    }

    public static String getActualVoicePath(org.json.JSONObject response) throws JSONException {
        return AppConfig.QINIU_AUDIO_PATH + response.getString("key");
    }

    /**
     * 清除数据库的所有数据
     */
    public static void restoreDB() {
        DBManager.newInstance().getDaoSession().getUserEntityDao().deleteAll();
        DBManager.newInstance().getDaoSession().getFriendsEntityDao().deleteAll();
        DBManager.newInstance().getDaoSession().getGroupEntityDao().deleteAll();
        DBManager.newInstance().getDaoSession().getMemberEntityDao().deleteAll();
        DBManager.newInstance().getDaoSession().getConversationEntityDao().deleteAll();
        DBManager.newInstance().getDaoSession().getMessageEntityDao().deleteAll();
    }

    /**
     * 根据用户名清除对应的数据
     *
     * @param userId
     */
    public static void restoreDB(int userId) {
        //清除好友分组
        //清除群分组

    }

    public static void updateUser(List<MemberListVo.UserFriendsBean> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                MemberListVo.UserFriendsBean bean = list.get(i);
                MemberEntityDao dao = DBManager.newInstance().getDaoSession().getMemberEntityDao();
                List<MemberEntity> entities = dao.queryBuilder().where(MemberEntityDao.Properties.UserId.eq(getSelfUserId()), MemberEntityDao.Properties.MemberId.eq(bean.userId)).list();
                if (entities != null && entities.size() > 0) {
                    for (int j = 0; j < entities.size(); j++) {
                        MemberEntity entity = entities.get(j);
                        entity.avatar = bean.userAvatar;
                        entity.nick = bean.nick;
                        entity.remark = bean.remark;
                        dao.update(entity);
                    }
                }
            }
        }
    }

    /***
     * 通过接口更新好友数据
     * @param list
     */
    public static void updateOrInsertUser(List<MemberListVo.UserFriendsBean> list) {
        if (list != null && list.size() > 0) {
            FriendsEntity friendsEntity = new FriendsEntity();
            //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
            friendsEntity.id = Long.valueOf(toHash(String.valueOf(getSelfUserId()) + String.valueOf(getSelfUserId())));
            friendsEntity.userId = getSelfUserId(); //外键 用户id
            friendsEntity.groupId = String.valueOf(getSelfUserId());  //群组id
            friendsEntity.name = "我的好友"; //群名称
            DBManager.newInstance().getDaoSession().getFriendsEntityDao().insertOrReplace(friendsEntity);

            MemberEntityDao dao = DBManager.newInstance().getDaoSession().getMemberEntityDao();
            for (int i = 0; i < list.size(); i++) {
                MemberListVo.UserFriendsBean bean = list.get(i);
                MemberEntity memberEntity = new MemberEntity();

                memberEntity.id = Long.valueOf(toHash(String.valueOf(friendsEntity.groupId) + String.valueOf(bean.userId)));
                memberEntity.friendsId = friendsEntity.id;
                ;  //外键 关联好友分组
                memberEntity.userId = friendsEntity.userId;   //关联用户
                memberEntity.memberId = String.valueOf(bean.userName);  //好友id
                memberEntity.name = bean.userName;    //好友头像
                memberEntity.avatar = bean.userAvatar;    //好友头像
                memberEntity.nick = bean.nick;        //好友昵称
                memberEntity.remark = bean.remark;  //备注

                dao.insertOrReplace(memberEntity);
            }
        }
        EventBus.getDefault().post(new ResponseChanged(ResponseIml.SIGN_PROCESS_LOGIN_RESPONSE_SUCCESS));
    }

    public static void updateOrInsertUser(UserGroupResponse response) {
        if (response != null && response.data != null) {
            ImHelper.clearFriendGroup();
            //群组列表
            if (response.data.groups != null && response.data.groups.size() > 0) {
                for (int i = 0; i < response.data.groups.size(); i++) {
                    LoginResponse.DataBean.UserBean.GroupsBean groupsBean = response.data.groups.get(i);
                    if (groupsBean != null && !TextUtils.isEmpty(groupsBean.group_id)) { //过滤空群组的情况
                        //存储群组信息
                        GroupEntity groupEntity = new GroupEntity();
                        //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
                        groupEntity.id = Long.valueOf(toHash(String.valueOf(groupsBean.group_id) + String.valueOf(getSelfUserId())));
                        groupEntity.userId = getSelfUserId(); //外键 用户id
                        groupEntity.groupId = groupsBean.group_id;  //群组id
                        groupEntity.name = groupsBean.name; //群名称
                        long l1 = DBManager.newInstance().getDaoSession().getGroupEntityDao().insertOrReplace(groupEntity);
                        LogUtils.info("--> 更新群组分组 " + l1);

                        if (groupsBean.users != null && groupsBean.users.size() > 0) {
                            for (int j = 0; j < groupsBean.users.size(); j++) {
                                LoginResponse.DataBean.UserBean.UserChildBean memberBean = groupsBean.users.get(j);
                                //存储群成员信息
                                MemberEntity memberEntity = new MemberEntity();
                                //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
                                memberEntity.id = Long.valueOf(toHash(String.valueOf(groupEntity.groupId) + String.valueOf(memberBean.id)));
                                memberEntity.groupId = groupEntity.id;  //外键 群组id
                                memberEntity.userId = groupEntity.userId;   //关联用户   不需要关联用户id  没关联 表示是群关系

                                memberEntity.memberId = memberBean.id;  //好友id
                                memberEntity.avatar = memberBean.avatar;    //头像
                                memberEntity.nick = memberBean.nick;        //昵称
                                long l2 = DBManager.newInstance().getDaoSession().getMemberEntityDao().insertOrReplace(memberEntity);
                                LogUtils.info("--> 更新群组成员 " + l2);
                            }
                        }
                    }
                }
            }

//            //好友列表
//            if (response.data.friends != null && response.data.friends.size() > 0) {
//                //好友分组
//                for (int i = 0; i < response.data.friends.size(); i++) {
//                    LoginResponse.DataBean.UserBean.FriendsBean friendsBean = response.data.friends.get(i);
//                    if (friendsBean.group_id != null) {  //过滤好友分组为空的情况
//                        //存储好友分组信息
//                        FriendsEntity friendsEntity = new FriendsEntity();
//                        //取好友分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
//                        friendsEntity.id = Long.valueOf(toHash(String.valueOf(friendsBean.group_id) + String.valueOf(getSelfUserId())));
//                        friendsEntity.userId = getSelfUserId();
//                        friendsEntity.groupId = friendsBean.group_id;
//                        friendsEntity.name = friendsBean.name;
//                        long l1 = DBManager.newInstance().getDaoSession().getFriendsEntityDao().insertOrReplace(friendsEntity);
//                        LogUtils.info("--> 更新好友分组 " + l1);
//
//                        if (friendsBean.users != null && friendsBean.users.size() > 0) {
//                            for (int j = 0; j < friendsBean.users.size(); j++) {
//                                LoginResponse.DataBean.UserBean.UserChildBean memberBean = friendsBean.users.get(j);
//                                //存储好友分组下好友信息
//                                MemberEntity memberEntity = new MemberEntity();
//                                //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
//                                memberEntity.id = Long.valueOf(toHash(String.valueOf(friendsEntity.groupId) + String.valueOf(memberBean.id)));
//                                memberEntity.friendsId = friendsEntity.id;  //外键 关联好友分组
//                                memberEntity.userId = friendsEntity.userId;   //关联用户
//
//                                memberEntity.memberId = memberBean.id;  //好友id
//                                memberEntity.avatar = memberBean.avatar;    //好友头像
//                                memberEntity.nick = memberBean.nick;        //好友昵称
//                                long l2 = DBManager.newInstance().getDaoSession().getMemberEntityDao().insertOrReplace(memberEntity);
//                                LogUtils.info("--> 更新好友数据 " + l2);
//
//                            }
//                        }
//                    }
//                }
//            }


        }
    }


    public static void updateOrInsertUser(MemberVo memberVo, LoginResponse response) {
        //存储用户信息
        UserEntity userEntity = new UserEntity();
        userEntity.id = Long.valueOf(memberVo.userInfo.userId);
//        userEntity.userImId = response.data.user.id;
        userEntity.userName = memberVo.userInfo.userName;
        userEntity.userNumber = memberVo.userInfo.userNumber;
        userEntity.nick = memberVo.userInfo.nick;
        userEntity.userAvatar = memberVo.userInfo.userAvatar;
        userEntity.phone = memberVo.userInfo.phone;
        userEntity.password = memberVo.userInfo.password;
        userEntity.salt = memberVo.userInfo.salt;
        userEntity.userType = memberVo.userInfo.userType;
        userEntity.userStatus = memberVo.userInfo.userStatus;
        userEntity.userQrUrl = memberVo.userInfo.userQrUrl;
        userEntity.userLevelId = memberVo.userInfo.userLevelId;
        userEntity.deviceToken = memberVo.userInfo.deviceToken;
        userEntity.createdTime = memberVo.userInfo.createdTime;
        userEntity.updatedTime = memberVo.userInfo.updatedTime;

        long l = DBManager.newInstance().getDaoSession().getUserEntityDao().insertOrReplace(userEntity);

        if (response.data != null) {
            ImHelper.clearFriendGroup();
            //群组列表
            if (response.data.user.groups != null && response.data.user.groups.size() > 0) {
                for (int i = 0; i < response.data.user.groups.size(); i++) {
//            for (int i = 0; i < 1; i++) {
                    LoginResponse.DataBean.UserBean.GroupsBean groupsBean = response.data.user.groups.get(i);
                    if (groupsBean != null && !TextUtils.isEmpty(groupsBean.group_id)) { //过滤空群组的情况
                        //存储群组信息
                        GroupEntity groupEntity = new GroupEntity();
                        //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
                        groupEntity.id = Long.valueOf(toHash(String.valueOf(groupsBean.group_id) + String.valueOf(userEntity.id)));
                        groupEntity.userId = userEntity.id; //外键 用户id
                        groupEntity.groupId = groupsBean.group_id;  //群组id
                        groupEntity.name = groupsBean.name; //群名称
                        groupEntity.avatar = groupsBean.avatar; //群头像
                        long l1 = DBManager.newInstance().getDaoSession().getGroupEntityDao().insertOrReplace(groupEntity);
                        LogUtils.info("--> 更新群组分组 " + l1);

                        if (groupsBean.users != null && groupsBean.users.size() > 0) {
                            for (int j = 0; j < groupsBean.users.size(); j++) {
                                LoginResponse.DataBean.UserBean.UserChildBean memberBean = groupsBean.users.get(j);
                                //存储群成员信息
                                MemberEntity memberEntity = new MemberEntity();
                                //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
                                memberEntity.id = Long.valueOf(toHash(String.valueOf(groupEntity.groupId) + String.valueOf(memberBean.id)));
                                memberEntity.groupId = groupEntity.id;  //外键 群组id
                                memberEntity.userId = userEntity.id;   //关联用户   不需要关联用户id  没关联 表示是群关系

                                memberEntity.memberId = memberBean.id;  //好友id
                                memberEntity.avatar = memberBean.avatar;    //头像
                                memberEntity.nick = memberBean.nick;        //昵称
                                long l2 = DBManager.newInstance().getDaoSession().getMemberEntityDao().insertOrReplace(memberEntity);
                                LogUtils.info("--> 更新群组成员 " + l2);

                            }
                        }
                    }
                }
            }

            //好友列表
//            if (response.data.user.friends != null && response.data.user.friends.size() > 0) {
//                //好友分组
//                for (int i = 0; i < response.data.user.friends.size(); i++) {
//                    LoginResponse.DataBean.UserBean.FriendsBean friendsBean = response.data.user.friends.get(i);
//                    if (friendsBean.group_id != null) {  //过滤好友分组为空的情况
//                        //存储好友分组信息
//                        FriendsEntity friendsEntity = new FriendsEntity();
//                        //取好友分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
//                        friendsEntity.id = Long.valueOf(toHash(String.valueOf(friendsBean.group_id) + String.valueOf(userEntity.id)));
//                        friendsEntity.userId = userEntity.id;
//                        friendsEntity.groupId = friendsBean.group_id;
//                        friendsEntity.name = friendsBean.name;
//                        long l1 = DBManager.newInstance().getDaoSession().getFriendsEntityDao().insertOrReplace(friendsEntity);
//                        LogUtils.info("--> 更新好友分组 " + l1);
//
//                        if (friendsBean.users != null && friendsBean.users.size() > 0) {
//                            for (int j = 0; j < friendsBean.users.size(); j++) {
//                                LoginResponse.DataBean.UserBean.UserChildBean memberBean = friendsBean.users.get(j);
//                                //存储好友分组下好友信息
//                                MemberEntity memberEntity = new MemberEntity();
//                                //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
//                                memberEntity.id = Long.valueOf(toHash(String.valueOf(friendsEntity.groupId) + String.valueOf(memberBean.id)));
//                                memberEntity.friendsId = friendsEntity.id;  //外键 关联好友分组
//                                memberEntity.userId = userEntity.id;   //关联用户
//
//                                memberEntity.memberId = memberBean.id;  //好友id
//                                memberEntity.avatar = memberBean.avatar;    //好友头像
//                                memberEntity.nick = memberBean.nick;        //好友昵称
//                                long l2 = DBManager.newInstance().getDaoSession().getMemberEntityDao().insertOrReplace(memberEntity);
//                                LogUtils.info("--> 更新好友数据 " + l2);
//
//                            }
//                        }
//                    }
//                }
//            }


        }
    }

    public static void insertFriend(int hashCode, int userId, String userName, String userAvatar, String nick) {
        //存储好友分组下好友信息
        MemberEntity memberEntity = new MemberEntity();
        //取分组id 和 用户id的hash值  保证唯一 以便添加时动态替换
        memberEntity.id = Long.valueOf(hashCode + userId);
        memberEntity.userId = getSelfUserId();   //关联用户

        memberEntity.memberId = userName;  //好友id
        memberEntity.avatar = userAvatar;    //好友头像
        memberEntity.nick = nick;        //好友昵称
        DBManager.newInstance().getDaoSession().getMemberEntityDao().insertOrReplace(memberEntity);
    }

    /**
     * 清除好友和群组信息
     */
    public static void clearFriendGroup() {
        DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
        DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
        DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder().where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public static void clearFriend() {
        DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
        DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder().where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public static void deleteGroup(String groupId) {
        DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.GroupId.eq(groupId), GroupEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    public static void deleteFriend(String memberId) {
        DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(memberId),
                MemberEntityDao.Properties.UserId.eq(getSelfUserId())).buildDelete().executeDeleteWithoutDetachingEntities();
    }

    /**
     * 获取好友列表
     *
     * @return
     */
    public static List<MemberEntity> getAllFriendList() {
        List<MemberEntity> list = new ArrayList<>();
        List<FriendsEntity> friendsEntityList = DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder().where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (friendsEntityList != null && friendsEntityList.size() > 0) {
            for (int i = 0; i < friendsEntityList.size(); i++) {
                FriendsEntity entity = friendsEntityList.get(i);
                entity.list = DBManager.newInstance().getDaoSession().getMemberEntityDao()._queryFriendsEntity_List(entity.id);
                list.addAll(entity.list);
            }
        }
        LogUtils.info("--> MemberEntity " + list.toString());
        return list;
    }

    /**
     * 获取好友列表
     *
     * @return
     */
    public static List<MemberEntity> getFriendList() {
        List<MemberEntity> list = new ArrayList<>();
        List<FriendsEntity> friendsEntityList = DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder().where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (friendsEntityList != null && friendsEntityList.size() > 0) {
            for (int i = 0; i < friendsEntityList.size(); i++) {
                FriendsEntity entity = friendsEntityList.get(i);
                entity.list = DBManager.newInstance().getDaoSession().getMemberEntityDao()._queryFriendsEntity_List(entity.id);
                list.addAll(entity.list);
            }
        }
        LogUtils.info("--> MemberEntity " + list.toString());
        return list;
    }

    /**
     * 获取好友列表
     *
     * @return
     */
    public static List<MemberEntity> getFriendList(String keyword) {
        List<MemberEntity> list = new ArrayList<>();
        List<FriendsEntity> friendsEntityList = DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder()
                .where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (friendsEntityList != null && friendsEntityList.size() > 0) {
            for (int i = 0; i < friendsEntityList.size(); i++) {
                FriendsEntity entity = friendsEntityList.get(i);
                entity.list = DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder()
                        .where(MemberEntityDao.Properties.FriendsId.eq(entity.id), MemberEntityDao.Properties.Nick.like(keyword)).list();
                list.addAll(entity.list);
            }
        }
        return list;
    }

    /**
     * 获取群组列表
     *
     * @return
     */
    public static List<GroupEntity> getGroupList() {
        List<GroupEntity> list = new ArrayList<>();
        List<GroupEntity> groupEntityList = DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (groupEntityList != null && groupEntityList.size() > 0) {
            list.addAll(groupEntityList);
        }
        LogUtils.info("--> GroupEntity " + list.toString());
        return list;
    }

    /**
     * 获取群组列表
     *
     * @return
     */
    public static List<GroupEntity> getGroupList(String keyword) {
        List<GroupEntity> list = new ArrayList<>();
        List<GroupEntity> groupEntityList = DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder()
                .where(GroupEntityDao.Properties.UserId.eq(getSelfUserId()), GroupEntityDao.Properties.Name.like(keyword)).list();
        if (groupEntityList != null && groupEntityList.size() > 0) {
            list.addAll(groupEntityList);
        }
        return list;
    }


    public static List<IEntity> getContactList() {
        List<IEntity> list = new ArrayList<>();

        List<GroupEntity> groupEntityList = DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (groupEntityList != null && groupEntityList.size() > 0) {
            list.addAll(groupEntityList);
        }

        List<FriendsEntity> friendsEntityList = DBManager.newInstance().getDaoSession().getFriendsEntityDao().queryBuilder().where(FriendsEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (friendsEntityList != null && friendsEntityList.size() > 0) {
            for (int i = 0; i < friendsEntityList.size(); i++) {
                FriendsEntity entiry = friendsEntityList.get(i);
                entiry.list = DBManager.newInstance().getDaoSession().getMemberEntityDao()._queryFriendsEntity_List(entiry.id);
            }
            list.addAll(friendsEntityList);
        }

        return list;
    }

    /**
     * 更新或插入会话
     *
     * @param imResponse
     */
    public static void updateOrInsertConversation(ImResponse imResponse) {
        if (imResponse instanceof ChatResponse) {
            updateOrInsertConversation((ChatResponse) imResponse);
        }
    }

    public static ConversationEntity generateConversation(ConversationEntity entity) {
        if (entity.chatType == ChatType.CHAT_TYPE_PUBLIC.getNumber()) {
            ConversationEntity conversation = generateConversation(entity.sessionIdStr);
            if (conversation != null) {
                return conversation;
            }
        }else if(entity.chatType == ChatType.CHAT_TYPE_PRIVATE.getNumber()){
            MemberEntity memberEntity = queryMemberEntity(entity.sessionIdStr);
            if(!TextUtils.isEmpty(memberEntity.remark)) {
                entity.name = memberEntity.remark;
            }
            entity.avatar = memberEntity.avatar;
            DBManager.newInstance().getDaoSession().getConversationEntityDao().updateInTx(entity);
        }
        return entity;
    }




    public static ConversationEntity generateConversation(String groupNumber) {
        List<GroupEntity> list = DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.GroupId.eq(groupNumber), GroupEntityDao.Properties.UserId.eq(ImHelper.getSelfUserId())).list();

        if (list != null && list.size() > 0) {
            return generateConversation(list.get(0));
        }
        return null;
    }

    /**
     * 生成会话对象
     *
     * @param group
     * @return
     */
    public static ConversationEntity generateConversation(GroupEntity group) {
        ConversationEntity entity = new ConversationEntity();
        entity.sessionIdStr = group.groupId;
        entity.userId = group.userId;
        entity.chatType = ChatType.CHAT_TYPE_PUBLIC.getNumber();
        entity.id = Long.valueOf(toHash(String.valueOf(entity.sessionIdStr) + String.valueOf(entity.userId) + String.valueOf(entity.chatType)));
        entity.name = group.name;

        return entity;
    }

    /**
     * 生成客服会话对象
     *
     * @return
     */
    public static ConversationEntity generateServiceConversation() {
        ConversationEntity entity = new ConversationEntity();
        entity.sessionIdStr = AppConfig.NAME_ADMIN;
        entity.userId = getSelfUserId();
        entity.chatType = ChatType.CHAT_TYPE_PRIVATE.getNumber();
        entity.id = Long.valueOf(toHash(String.valueOf(entity.sessionIdStr) + String.valueOf(entity.userId) + String.valueOf(entity.chatType)));
        entity.name = "在线客服";
        return entity;
    }

    /**
     * 生成好友会话对象
     *
     * @param member
     * @return
     */
    public static ConversationEntity generateConversation(MemberEntity member) {
        ConversationEntity entity = new ConversationEntity();
        entity.sessionIdStr = member.memberId;
        entity.userId = member.userId;
        entity.chatType = ChatType.CHAT_TYPE_PRIVATE.getNumber();
        entity.id = Long.valueOf(toHash(String.valueOf(entity.sessionIdStr) + String.valueOf(entity.userId) + String.valueOf(entity.chatType)));
        entity.name = TextUtils.isEmpty(member.remark) ? member.nick : member.remark;
        entity.avatar = member.avatar;

        return entity;
    }

    public static void updateOrInsertConversation(ConversationEntity entity) {
        DBManager.newInstance().getDaoSession().getConversationEntityDao().insertOrReplace(entity);
    }


    public static ConversationEntity updateOrInsertConversation(ChatResponse response) {
        ConversationEntity entity = new ConversationEntity();
        long userId = getSelfUserId();
        switch (response.data.chatType) {
            case 1:  //群聊
                entity.sessionIdStr = response.data.group_id;
                GroupEntity group = queryGroupEntity(response.data.group_id);
                if (group == null) {
                    entity.name = response.data.group_id;
                } else {
                    entity.name = group.name;
                    entity.avatar = group.avatar;
                }

                if (isSelf(response.data.from)) {
                    entity.latestNick = getSelfNick();
                    entity.latestAvatar = getSelfAvatar();

                } else {
                    MemberEntity memberEntity = queryMemberEntity(response.data.from);
                    if (memberEntity != null) {
                        entity.latestNick = memberEntity.nick;
                        entity.latestAvatar = memberEntity.avatar;
//                        if(!TextUtils.isEmpty(memberEntity.remark)) {
//
//                        }
                        entity.latestName = memberEntity.name;
                    }
                }

                break;
            case 2:  //私聊
                if (isSelf(response.data.from)) { //自己发送的
                    entity.sessionIdStr = response.data.to;
                    entity.latestNick = getSelfNick();
                    entity.latestAvatar = getSelfAvatar();

                    MemberEntity member = queryMemberEntity(response.data.to);
                    if (member == null) {
                        entity.name = response.data.to;
                    } else {
                        if (!TextUtils.isEmpty(member.remark)) {
                            entity.name = member.remark;
                        } else {
                            entity.name = TextUtils.isEmpty(member.nick) ? member.memberId : member.nick;
                        }
                        entity.avatar = member.avatar;
                    }
                } else { //接收的
                    entity.sessionIdStr = response.data.from;
                    MemberEntity member = queryMemberEntity(response.data.from);

                    if (member != null) {
                        LogUtils.info("--> MemberEntity " + member.toString());
                        entity.latestNick = member.nick;
                        entity.latestAvatar = member.avatar;
                        entity.latestName = TextUtils.isEmpty(member.nick) ? member.memberId : member.nick;
                        entity.latestRemark = member.remark;
                        if (!TextUtils.isEmpty(member.remark)) {
                            entity.name = member.remark;
                        } else {
                            entity.name = TextUtils.isEmpty(member.nick) ? member.memberId : member.nick;
                        }
                        entity.avatar = member.avatar;
                    } else {
                        entity.name = response.data.from;
                    }
                }
                break;
            default:
                entity.sessionIdStr = response.data.from;
                break;
        }
        entity.chatType = response.data.chatType;
        entity.userId = Long.valueOf(userId);
        entity.id = Long.valueOf(toHash(String.valueOf(entity.sessionIdStr) + String.valueOf(entity.userId) + String.valueOf(entity.chatType)));
        entity.latestTime = response.data.createTime;
        entity.latestMsg = response.data.content;
        entity.latestMsgType = response.data.msgType;


        DBManager.newInstance().getDaoSession().getConversationEntityDao().insertOrReplace(entity);
        return entity;
    }


    public static MemberEntity queryMemberEntity(String memberId) {
        //先判断是否时好友
        List<MemberEntity> data = DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(memberId),
                MemberEntityDao.Properties.UserId.eq(getSelfUserId()), MemberEntityDao.Properties.FriendsId.isNotNull()).list();
        if (data != null && data.size() > 0) {
            return data.get(0);
        }

        //再取所有信息
        QueryBuilder<MemberEntity> builder = DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(memberId), MemberEntityDao.Properties.UserId.eq(getSelfUserId()));
        List<MemberEntity> list = builder.list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static GroupEntity queryGroupEntity(String groupId) {
        QueryBuilder<GroupEntity> builder = DBManager.newInstance().getDaoSession().getGroupEntityDao().queryBuilder().where(GroupEntityDao.Properties.GroupId.eq(groupId), GroupEntityDao.Properties.UserId.eq(getSelfUserId()));
        List<GroupEntity> list = builder.list();
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }


    public static int toHash(String key) {
        int arraySize = 11113; // 数组大小一般取质数
        int hashCode = 0;
        for (int i = 0; i < key.length(); i++) { // 从字符串的左边开始计算
            int letterValue = key.charAt(i) - 96;// 将获取到的字符串转换成数字，比如a的码值是97，则97-96=1
            // 就代表a的值，同理b=2；
            hashCode = ((hashCode << 5) + letterValue) % arraySize;// 防止编码溢出，对每步结果都进行取模运算
        }
        return Math.abs(hashCode);
    }


    public static void updateOrInsertMessage(ImResponse response) {
        if (response instanceof ChatResponse) {
            updateOrInsertMessage((ChatResponse) response);
        }
    }

    /**
     * 私聊时主动发送信息保存
     *
     * @param entity
     */
    public static void insertMessage(MessageEntity entity) {
        DBManager.newInstance().getDaoSession().getMessageEntityDao().insertOrReplaceInTx(entity);
    }

    /**
     * 处理离线消息
     *
     * @param response
     */
    public static void insertMessage(OfflineMessageResponse response) {
        if (response.data != null) {
            List<ChatResponse> list = new ArrayList<>();
            if (!TextUtils.isEmpty(response.data.groups)) {
                JSONObject object = JSON.parseObject(response.data.groups);
                Iterator<String> sIterator = object.keySet().iterator();
                while (sIterator.hasNext()) {
                    String key = sIterator.next();
                    String value = object.getString(key);
                    if (!TextUtils.isEmpty(value)) {
                        List<ChatResponse.DataBean> temp = JSON.parseArray(value, ChatResponse.DataBean.class);
                        if (temp != null && temp.size() > 0) {
                            for (int i = 0; i < temp.size(); i++) {
                                ChatResponse bean = new ChatResponse();
                                bean.data = temp.get(i);
                                bean.command = Command.COMMAND_CHAT_REQ.getNumber();
                                list.add(bean);
                            }
                        }
                    }
                }
            }
            if (!TextUtils.isEmpty(response.data.friends)) {
                if (!TextUtils.isEmpty(response.data.friends)) {
                    JSONObject object = JSON.parseObject(response.data.friends);
                    Iterator<String> sIterator = object.keySet().iterator();
                    while (sIterator.hasNext()) {
                        String key = sIterator.next();
                        String value = object.getString(key);
                        if (!TextUtils.isEmpty(value)) {
                            List<ChatResponse.DataBean> temp = JSON.parseArray(value, ChatResponse.DataBean.class);
                            if (temp != null && temp.size() > 0) {
                                for (int i = 0; i < temp.size(); i++) {
                                    ChatResponse bean = new ChatResponse();
                                    bean.data = temp.get(i);
                                    bean.command = Command.COMMAND_CHAT_REQ.getNumber();
                                    list.add(bean);
                                }
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < list.size(); i++) {
                updateOrInsertMessage(list.get(i));
            }
        }
    }

    /**
     * 撤回消息
     *
     * @param response
     */
    public static boolean updateRecallMessage(ChatResponse response) {
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        List<MessageEntity> list = null;
        //通过消息id查询
        try {
            list = dao.queryBuilder().where(MessageEntityDao.Properties.MessageId.eq(response.data.content),
                    MessageEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        } catch (Exception e) {
        }
        //消息id未查询 通过消息时间和发送人姓名查询
        if (list == null || list.size() <= 0) {
            list = dao.queryBuilder().where(MessageEntityDao.Properties.CreateTime.eq(response.data.createTime), MessageEntityDao.Properties.From.eq(response.data.from),
                    MessageEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        }

        if (list != null && list.size() > 0) {
            //
            MessageEntity entity = list.get(0);
            if (isSelf(entity.from)) {
                entity.content = "你撤回了一条消息";
            } else {
                MemberEntity memberEntity = queryMemberEntity(entity.from);
                if (memberEntity != null) {
                    String name = entity.from;
                    if (!TextUtils.isEmpty(entity.fromRemark)) {
                        name = entity.fromRemark;
                    } else if (!TextUtils.isEmpty(entity.fromNick)) {
                        name = entity.fromNick;
                    } else if (!TextUtils.isEmpty(entity.fromName)) {
                        name = entity.fromName;
                    }
                    entity.content = "\"" + name + "\"" + "撤回了一条消息";
                } else {
                    entity.content = "\"" + entity.from + "\"" + "撤回了一条消息";
                }

            }

            response.data.content = entity.content;

            //更新消息id
            if (TextUtils.isEmpty(entity.messageId)) {
                entity.messageId = response.data.content;
            }

            //更新消息命令
            entity.cmd = response.data.cmd;

            //执行更新
            dao.updateInTx(entity);

            return true;
        }

        return false;
    }

    /**
     * 更新当前的撤回消息
     *
     * @param entity
     */
    public static void updateRecallMessage(MessageEntity entity) {
        entity.cmd = Command.COMMAND_CANCEL_MSG_REQ.getNumber();
        entity.content = "你撤回了一条消息";
        DBManager.newInstance().getDaoSession().getMessageEntityDao().updateInTx(entity);
    }

    /**
     * 主动更新自己撤回消息会话信息
     *
     * @param entity
     * @param messageEntity
     */
    public static void updateRecallSelfConversation(ConversationEntity entity, MessageEntity messageEntity) {
        entity.latestAvatar = messageEntity.fromAvatar;
        entity.latestName = messageEntity.fromName;
        entity.latestNick = messageEntity.fromNick;
        entity.chatType = messageEntity.chatType;
        entity.userId = getSelfUserId();
        entity.id = Long.valueOf(toHash(String.valueOf(entity.sessionIdStr) + String.valueOf(entity.userId) + String.valueOf(entity.chatType)));
        entity.latestTime = getTimestamp();
        entity.latestMsg = messageEntity.content;
        entity.latestMsgType = messageEntity.msgType;
        DBManager.newInstance().getDaoSession().getConversationEntityDao().updateInTx(entity);
    }


    /**
     * 更新消息
     *
     * @param response
     */
    public static void updateOrInsertMessage(ChatResponse response) {
        long conversationId = 0;
        ConversationEntity conversation = updateOrInsertConversation(response);
        if (conversation != null) {
            conversationId = conversation.id;
        }

        MessageEntity entity = new MessageEntity();
        entity.conversationId = conversationId;
        entity.userId = getSelfUserId();

        entity.chatType = response.data.chatType;
        entity.cmd = response.data.cmd;
        entity.content = response.data.content;
        entity.createTime = response.data.createTime;
        entity.group_id = response.data.group_id;
        entity.messageId = response.data.id;
        entity.msgType = response.data.msgType;
        entity.from = response.data.from;
        entity.to = response.data.to;
        if (response.data.chatType == ChatType.CHAT_TYPE_PUBLIC.getNumber()) {
            //群聊
            if (isSelf(entity.from)) {  //自己发送的
                entity.isOwnSend = 1;
                entity.fromAvatar = getSelfAvatar();
                entity.fromNick = getSelfNick();
                entity.isFailed = 0; //群聊不存在失败情况
            } else { //非自己发送的
                MemberEntity memberEntity = queryMemberEntity(entity.from);
                if (memberEntity != null) {
                    entity.fromAvatar = memberEntity.avatar;
                    entity.fromNick = memberEntity.nick;
                } else {
                    entity.fromNick = response.data.from;
                }
            }
        } else if (response.data.chatType == ChatType.CHAT_TYPE_PRIVATE.getNumber()) {
//            MemberEntity memberEntity;
            //私聊
            if (isSelf(entity.from)) {
                //自己发的
                entity.isRead = 1;
                entity.isOwnSend = 1;
                entity.fromAvatar = getSelfAvatar();
                entity.fromNick = getSelfNick();
//                memberEntity = queryMemberEntity(entity.to);
//                if (memberEntity != null) {
//                    entity.toAvatar = memberEntity.avatar;
//                    entity.toNick = memberEntity.nick;
//                }
                entity.toAvatar = conversation.avatar;
                entity.toNick = conversation.name;
            } else {
                //接收的
                entity.toAvatar = getSelfAvatar();
                entity.toNick = getSelfNick();

                entity.fromAvatar = conversation.avatar;
                entity.fromNick = conversation.name;

//                memberEntity = queryMemberEntity(entity.from);
//                if (memberEntity != null) {
//                    entity.fromAvatar = memberEntity.avatar;
//                    entity.fromNick = memberEntity.nick;
//                }
            }

        }

        //非自己发送的情况下 添加到数据库
        if (!isSelf(entity.from)) {
            DBManager.newInstance().getDaoSession().getMessageEntityDao().insertOrReplaceInTx(entity);
        } else {
            //自己发送的  如果数据库已存在数据  更新数据 否则添加到数据库
            MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
            List<MessageEntity> list = dao.queryBuilder().where(MessageEntityDao.Properties.CreateTime.eq(entity.createTime), MessageEntityDao.Properties.From.eq(getSelf())).list();
            if (list != null && list.size() > 0) {
                LogUtils.i(" - - 查到消息");
                MessageEntity messageEntity = list.get(0);
                messageEntity.messageId = entity.messageId;
                dao.updateInTx(messageEntity);
            } else {
                LogUtils.i(" - - 未查到消息");
            }
        }

    }

    public static void setMessageIsRead(ConversationEntity entity) {
        getUnReadMessageList(entity);
    }

    /**
     * 获取未读消息
     *
     * @param entity
     * @return
     */
    public static List<MessageEntity> getUnReadMessageList(ConversationEntity entity) {
        List<MessageEntity> list = new ArrayList<>();
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        List<MessageEntity> data = dao.queryBuilder().where(MessageEntityDao.Properties.ConversationId.eq(entity.id), MessageEntityDao.Properties.IsRead.notEq(1)).list();
        if (data != null && data.size() > 0) {
            list.addAll(data);
            ImProcessor.setMessageIsRead(data);
        }
        return list;
    }

    public static List<MessageEntity> getLatestMessage() {
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        long index = dao.queryBuilder().count() - 1;
        return dao.queryBuilder().limit(1).offset((int) index).list();
    }

    /**
     * 标记消息为已读   此处需要通知会话列表刷新未读数目
     *
     * @param list
     */
    public static boolean setMessageIsRead(List<MessageEntity> list) {
        if (list != null && list.size() > 0) {
            for (MessageEntity entity : list) {
                entity.isRead = 1;
            }
            MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
            dao.updateInTx(list);
            return true;
        }
        return false;
    }

    /**
     * 获取消息    用于进入会话页面
     *
     * @param entity
     * @param page
     * @param offset
     * @return
     */
    public static List<MessageEntity> getMessageList(ConversationEntity entity, int page, int offset) {
        setMessageIsRead(entity); //全部标记已读
        List<MessageEntity> list = new ArrayList<>();
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        QueryBuilder<MessageEntity> builder = dao.queryBuilder().where(MessageEntityDao.Properties.ConversationId.eq(entity.id));

        long count = builder.count();
        int newOffset = (int) (count > 30 ? count - 30 : 0);
        List<MessageEntity> data = builder.limit(30).offset(newOffset).list();
//        List<MessageEntity> data = builder.limit(offset).offset(page * offset).list();
        if (data != null) {
            list.addAll(data);
        }
        return list;
    }

    public static QueryBuilder<MessageEntity> getMessageQueryBuilder(ConversationEntity entity) {
        setMessageIsRead(entity); //全部标记已读
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        return dao.queryBuilder().where(MessageEntityDao.Properties.ConversationId.eq(entity.id));
    }

    public static List<MessageEntity> getMessageList(QueryBuilder<MessageEntity> builder, int page, int limit) {
        List<MessageEntity> list = new ArrayList<>();
        if (builder != null) {
            int count = (int) builder.count();
            list = builder.limit(limit).offset(count - (page) * limit).list();
        }
        return list;
    }

    /**
     * 获取会话列表
     *
     * @return
     */
    public static List<ConversationEntity> getConversationList() {
        List<ConversationEntity> list = new ArrayList<>();
        QueryBuilder<ConversationEntity> builder = DBManager.newInstance().getDaoSession().getConversationEntityDao().queryBuilder();
        if (builder != null) {
            List<ConversationEntity> array = builder.where(ConversationEntityDao.Properties.UserId.eq(getSelfUserId())).orderDesc(ConversationEntityDao.Properties.LatestTime).list();
            if (array != null) {
                for (int i = 0; i < array.size(); i++) {
                    ConversationEntity entity = array.get(i);
                    entity.unReadNum = (int) DBManager.newInstance().getDaoSession().getMessageEntityDao().queryBuilder().where(MessageEntityDao.Properties.ConversationId.eq(entity.id), MessageEntityDao.Properties.IsRead.eq(0)).count();

                }
                list.addAll(array);
            }
        }
        return list;
    }

    public static boolean isFriend(String memberId) {
        QueryBuilder<MemberEntity> builder = DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(memberId), MemberEntityDao.Properties.UserId.eq(getSelfUserId()), MemberEntityDao.Properties.FriendsId.isNotNull());
        return builder != null && builder.count() > 0;
    }

    /**
     * 获取群组成员列表
     *
     * @param groupId
     * @return
     */
    public static List<MemberEntity> getGroupMember(String groupId) {
        return DBManager.newInstance().getDaoSession().getMemberEntityDao().queryBuilder().where(MemberEntityDao.Properties.GroupId.eq(groupId), MemberEntityDao.Properties.UserId.eq(getSelfUserId())).list();
    }

    public static void deleteMessageEntity(long conversationId) {
        MessageEntityDao dao = DBManager.newInstance().getDaoSession().getMessageEntityDao();
        List<MessageEntity> list = dao.queryBuilder().where(MessageEntityDao.Properties.ConversationId.eq(conversationId), MessageEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (list != null && list.size() > 0) {
            for (MessageEntity entity : list) {
                dao.delete(entity);
            }
        }
    }

    public static void deleteConversationEntity(long conversationId) {
        ConversationEntityDao dao = DBManager.newInstance().getDaoSession().getConversationEntityDao();
        dao.deleteByKey(conversationId);
    }

    /**
     * 更新会话列表群名称
     *
     * @param entity
     */
    public static void updateConversationEntity(ConversationEntity entity, String name, String avatar) {
        ConversationEntityDao dao = DBManager.newInstance().getDaoSession().getConversationEntityDao();
        List<ConversationEntity> list = dao.queryBuilder().whereOr(ConversationEntityDao.Properties.SessionIdStr.eq(entity.sessionIdStr), ConversationEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (list != null && list.size() > 0) {
            ConversationEntity conversationEntity = list.get(0);
            conversationEntity.name = name;
            conversationEntity.avatar = avatar;
            dao.update(conversationEntity);
        }
    }

    /**
     * 更新联系人列表 群名称
     *
     * @param groupId
     * @param name
     */
    public static void updateGroupEntity(String groupId, String name, String avatar) {
        GroupEntityDao dao = DBManager.newInstance().getDaoSession().getGroupEntityDao();
        List<GroupEntity> list = dao.queryBuilder().where(GroupEntityDao.Properties.GroupId.eq(groupId), GroupEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (list != null && list.size() > 0) {
            GroupEntity entity = list.get(0);
            entity.name = name;
            entity.avatar = avatar;
            dao.update(entity);
        }
    }

    /**
     * 更新联系人列表 群名称
     *
     * @param memberId
     * @param name
     */
    public static void updateMemberEntity(String memberId, String name, String avatar) {
        MemberEntityDao dao = DBManager.newInstance().getDaoSession().getMemberEntityDao();
        List<MemberEntity> list = dao.queryBuilder().where(MemberEntityDao.Properties.MemberId.eq(memberId), MemberEntityDao.Properties.UserId.eq(getSelfUserId())).list();
        if (list != null && list.size() > 0) {
            MemberEntity entity = list.get(0);
            entity.name = name;
            entity.avatar = avatar;
            dao.update(entity);
        }
    }

}
